<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\CourseRecommend;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class UserController extends BaseController
{

    public function login(Request $request)
    {
        $email = $request->input('email');
        $password = $request->input('password');
        if (empty($email) || empty($password)) {
            return $this->failResponse('邮箱或密码不能为空');
        }
        $user = User::where('email', $email)->first();
        if (!$user) {
            return $this->failResponse('用户不存在');
        }
        if ($user->password != md5($password)) {
            return $this->failResponse('密码错误');
        } else {
            $token = md5(time() . $email);
            User::where('id', $user->id)->update(['remember_token' => $token]);
            return $this->successResponse(['token' => $token]);
        }
    }

    public function checkLogin(Request $request)
    {
        $user = User::getInfoByToken();
        if ($user) {
            return $this->successResponse(true);
        } else {
            return $this->successResponse(false);
        }
    }

    public function getUserInfo(Request $request) {
        $user = User::getInfoByToken();
        $user->password = '';
        return $this->successResponse($user);
    }

    public function saveUserInfo(Request $request) {
        $user = User::getInfoByToken();
        $data = [
            'name' => $request->input('name'),
            'user_type' => $request->input('user_type'),
            'describe' => $request->input('describe'),
        ];
        if ($request->input('password')) {
            $data['password'] = md5($request->input('password'));
            $token = md5(time() . $user->email);
            $data['remember_token'] = $token;
        }
        User::where('id', $user->id)->update($data);
        return $this->successResponse($user);
    }

}
